package main

import (
	"gin_erik/internal/database"
	"gin_erik/pkg/middleware"
	"gin_erik/pkg/routes"
	"github.com/gin-gonic/gin"
	"gopkg.in/yaml.v3"
	"log"
	"os"
)

type Config struct {
	Server struct {
		Port string `yaml:"port"`
	} `yaml:"server"`
	Database struct {
		Host     string `yaml:"host"`
		Port     string `yaml:"port"`
		Username string `yaml:"username"`
		Password string `yaml:"password"`
		DBName   string `yaml:"dbname"`
	} `yaml:"database"`
}

func main() {
	config := loadConfig()
	database.InitDB(
		config.Database.Host,
		config.Database.Port,
		config.Database.Username,
		config.Database.Password,
		config.Database.DBName,
	)
	r := gin.Default()
	// 处理处理
	r.Use(middleware.ErrorHandler())
	// 处理404和405
	r.NoRoute(middleware.NotFoundHandler())
	r.NoMethod(middleware.MethodNotAllowedHandler())
	// 授权中间件、需要认证的接口、同时需要排除不需要认证的接口
	// 例如：
	// r.Use(middleware.Authorization([]string{"/api/users/list", "/api/users/detail/:id"}))
	r.Use(middleware.Authentication())
	r.Use(middleware.Logging())
	routes.SetupRoutes(r)
	err := r.Run(":" + config.Server.Port)
	if err != nil {
		log.Fatal(" server start failed")
	}
	log.Println("server start success")
}

// 加载配置文件
func loadConfig() Config {
	file, err := os.ReadFile("config/config.yaml")
	if err != nil {
		log.Fatalf("无法读取配置文件：%v", err)
	}
	var config Config
	err = yaml.Unmarshal(file, &config)
	if err != nil {
		log.Fatalf("无法解析配置文件：%v", err)
	}
	return config
}
